import { useMutation } from "react-relay";
import {useCallback, useState} from "react";
import { RecordSourceSelectorProxy, } from "relay-runtime";
import { PipingUnitInput } from "./__generated__/useUpdatePipingUnitMutation.graphql";
import {useToast} from "customize-easy-ui-component";

const graphql = require("babel-plugin-relay/macro");
//更新，后端服务器必须返回被改动的实体；同时前端必须内省有关的可能已经修改的字段，前端没有声明字段就无法立刻更新relay缓存。
//后端服务器也不需要关心把所有的受影响东西都要打包到接口输出中啊，前端可以根据内省机制获取已经变化的关联字段;只要是能够内省出来的信息。
const mutation = graphql`
  mutation useUpdatePipingUnitMutation($id: ID!,$inp: PipingUnitInput!) {
    buildPipingUnit(id: $id, inp: $inp) {
      id code name
    }
  }
`;

//TS不允许使用in作为回调函数参数名！所以graphQl接口参数名in不能用啊
/*根本不需要返回result，会自动缓存更新的，setResult可删除掉。
* */
export default function useUpdateDeviceMutation() {
  const [result, setResult] =useState(false);
  const [commit, isInFlight] = useMutation(mutation);
  const toast = useToast();
  return {
    call:useCallback(
      (id: string, inp:PipingUnitInput) => {
             //上面回调参数是 组件编辑器触发发过来的(text, userId)=>{};
        return commit({
          variables: {
            id, inp
          },
          updater: (store: RecordSourceSelectorProxy) => {
            const payload = store.getRootField("buildPipingUnit");
            if (!payload) {
              return;
            }
            //只能一个个字段的提取的。若想整个模型都提取出来就上onCompleted
           // const retId: any = payload.getValue("id");
            //console.log("跑到useCancellationTaskMutation1经Id=",retId);
            //sharedUpdater(store, userId, deletedIds);
          },
          //optimisticUpdater: (store: RecordSourceSelectorProxy) => { }
          onCompleted: (response) => {
            //必须把上面的updater:配置函数删除掉才能执行这个onCompleted配置函数!!
            //整个模型都提取出来;可是比上面的updater的时间会迟点的。
            const { buildPipingUnit } = response as { buildPipingUnit: any };
            setResult(buildPipingUnit);
            //console.log("跑到useCancellationTaskMutation2输出=", buildEQP);
          },
          onError: error => {
            //前端自己处理的报错也会跑到这里:
            //console.log("跑到useCancellationTaskMutation回onError1 =",error);
            setResult( false);
            toast({
              title: "后端应答了",
              subtitle: '报错＝'+error,
              intent: "error"
            });
          }
        });
      },
      [commit,toast]
    ),
    isInFlight,
    result
  };
}

